<template>
  <el-container class="center-container">
    <el-card class="info-container">
      <h2>员工列表</h2>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input v-model="searchQuery" placeholder="输入员工ID或姓名"></el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="searchEmployees">搜索</el-button>
        </el-col>
      </el-row>
      <el-table :data="employees" style="margin-top: 20px;">
        <el-table-column prop="employeeId" label="员工ID"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" @click="viewEmployeeDetails(scope.row.employeeId)">员工详情</el-button>
            <el-button @click="viewLeaves(scope.row.employeeId)">查看假期</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="totalEmployees"
        style="margin-top: 20px;">
      </el-pagination>
    </el-card>
  </el-container>
</template>

<script>
export default {
  data() {
    return {
      employees: [],
      currentPage: 1,
      pageSize: 10,
      totalEmployees: 0,
      searchQuery: '',
      searching: false // 用于标识是否在搜索状态
    };
  },
  mounted() {
    this.fetchEmployees();
  },
  methods: {
    async fetchEmployees() {
      try {
        const response = await this.$axios.get('/api/employees', {
          params: {
            page: this.currentPage,
            limit: this.pageSize
          }
        });
        this.employees = response.data.employees;
        this.totalEmployees = response.data.total;
      } catch (error) {
        console.error('Error fetching employees:', error);
      }
    },
    async searchEmployees(page = 1) {
      if (!Number.isInteger(page)) {
        page = 1;
      }
      this.currentPage = page; // 每次搜索时设置当前页码
      if (!this.searchQuery) {
        this.searching = false;
        this.fetchEmployees();
        return;
      }
      this.searching = true;
      try {
        if (isNaN(this.searchQuery)) {
          console.log(`Searching for employees with name: ${this.searchQuery}, page: ${this.currentPage}, limit: ${this.pageSize}`);
          const response = await this.$axios.get('/api/employee/search', {
            params: {
              name: this.searchQuery,
              page: this.currentPage,
              limit: this.pageSize
            }
          });
          if (response.data.status === 'success') {
            this.employees = response.data.employees;
            this.totalEmployees = response.data.total;
          } else {
            this.employees = [];
            this.totalEmployees = 0;
            this.$message.error(response.data.message);
          }
        } else {
          console.log(`Searching for employee with ID: ${this.searchQuery}`);
          const response = await this.$axios.get(`/api/employee/${this.searchQuery}`);
          if (response.data.employeeId) {
            this.$router.push(`/employee-and-salary/${this.searchQuery}`);
          } else {
            this.$message.error('Employee not found.');
          }
        }
      } catch (error) {
        console.error('Error searching employees:', error);
        this.$message.error('搜索失败，请重试');
      }
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      if (this.searching) {
        this.searchEmployees(page); // 在搜索状态下进行分页
      } else {
        this.fetchEmployees(); // 在非搜索状态下进行分页
      }
    },
    viewEmployeeDetails(employeeId) {
      this.$router.push(`/employee-and-salary/${employeeId}`);
    },
    viewLeaves(employeeId) {
      this.$router.push(`/leave/${employeeId}`);
    }
  }
};
</script>

<style scoped>
.center-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}
.info-container {
  border: 1px solid #dcdfe6;
  padding: 20px;
  border-radius: 5px;
  background-color: #f9f9f9;
  max-width: 900px;
  width: 100%;
}
.el-table th, .el-table td {
  padding: 8px;
}
</style>
